package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.CacheNames;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysDictDataFetcher;
import com.ruoyi.common.core.domain.entity.SysDictDataTable;
import com.ruoyi.common.core.domain.entity.dto.*;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.babyfish.jimmer.Page;
import org.babyfish.jimmer.sql.JSqlClient;
import org.babyfish.jimmer.sql.ast.mutation.SaveMode;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 字典 业务层处理
 *
 * @author ruoyi
 */

@Service
@RequiredArgsConstructor
public class SysDictDataServiceImpl implements ISysDictDataService {
//    @Autowired
//    private SysDictDataMapper dictDataMapper;

    private final JSqlClient sqlClient;

    /**
     * 根据条件分页查询字典数据
     *
     * @param input 字典数据信息
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictDataPageView> selectDictDataList(SysDictDataPageInput input) {
        SysDictDataTable dataTable = SysDictDataTable.$;
        return sqlClient.createQuery(dataTable)
                .where(dataTable.dictType().eqIf(input.getDictType()),
                        dataTable.status().eqIf(input.getStatus()),
                        dataTable.dictLabel().ilikeIf(input.getDictLabel())
                ).orderBy(dataTable.dictSort().asc())
                .select(dataTable.fetch(SysDictDataPageView.class))
                .execute();
    }

    /**
     * 根据字典类型和字典键值查询字典数据信息
     *
     * @param dictType  字典类型
     * @param dictValue 字典键值
     * @return 字典标签
     */
    @Override
    public String selectDictLabel(String dictType, String dictValue) {
        SysDictDataTable dataTable = SysDictDataTable.$;
        return sqlClient.createQuery(dataTable)
                .where(dataTable.dictType().eq(dictType), dataTable.dictValue().eq(dictValue))
                .select(dataTable.fetch(SysDictDataFetcher.$.dictLabel()))
                .fetchOne().dictLabel();
    }


    /**
     * 根据字典数据ID查询信息
     *
     * @param dictCode 字典数据ID
     * @return 字典数据
     */
    @Override
    public SysDictData selectDictDataById(String dictCode) {
        return sqlClient.findById(SysDictData.class, dictCode);
    }

    /**
     * 批量删除字典数据信息
     *
     * @param dictCodes 需要删除的字典数据ID
     */
    @Override
    public void deleteDictDataByIds(String[] dictCodes) {
        SysDictDataTable dataTable = SysDictDataTable.$;
        for (String dictCode : dictCodes) {
            SysDictData data = selectDictDataById(dictCode);
            sqlClient.deleteById(SysDictData.class, dictCode);
            List<SysDictDataCacheDTO> dictDatas = sqlClient.createQuery(dataTable)
                    .where(dataTable.dictType().eq(data.dictType()))
                    .select(dataTable.fetch(SysDictDataCacheDTO.class))
                    .execute();
            DictUtils.setDictCache(data.dictType(), dictDatas);
        }
    }


    /**
     * 新增保存字典数据信息
     *
     * @param data 字典数据信息
     * @return 结果
     */
    @Override
    @CachePut(cacheNames = CacheNames.SYS_DICT, key = "#data.dictType")
    public List<SysDictDataCacheDTO> insertDictData(SysDictDataSaveInput data) {
        SysDictDataTable dataTable = SysDictDataTable.$;
        int row = sqlClient.saveCommand(data).setMode(SaveMode.INSERT_ONLY).execute().getTotalAffectedRowCount();
        if (row > 0) {
            return sqlClient.createQuery(dataTable)
                    .where(dataTable.dictType().eq(data.getDictType()))
                    .orderBy(dataTable.dictSort().asc())
                    .select(dataTable.fetch(SysDictDataCacheDTO.class))
                    .execute();
        }
        throw new ServiceException("操作失败");
    }

    /**
     * 修改保存字典数据信息
     *
     * @param data 字典数据信息
     * @return 结果
     */
    @Override
    @CachePut(cacheNames = CacheNames.SYS_DICT, key = "#data.dictType")
    public List<SysDictDataCacheDTO> updateDictData(SysDictDataUpdateInput data) {
        SysDictDataTable dataTable = SysDictDataTable.$;
        int row = sqlClient.saveCommand(data)
                .setMode(SaveMode.UPDATE_ONLY)
                .execute()
                .getTotalAffectedRowCount();
        if (row > 0) {
            return sqlClient.createQuery(dataTable)
                    .where(dataTable.dictType().eq(data.getDictType()))
                    .orderBy(dataTable.dictSort().asc())
                    .select(dataTable.fetch(SysDictDataCacheDTO.class))
                    .execute();
        }
        throw new ServiceException("操作失败");
    }

    @Override
    public Page<SysDictDataPageView> selectDictDataPage(SysDictDataPageInput input, PageQuery pageQuery) {
        SysDictDataTable dataTable = SysDictDataTable.$;
        return sqlClient.createQuery(dataTable)
                .where(dataTable.dictType().eqIf(input.getDictType()),
                        dataTable.status().eqIf(input.getStatus()),
                        dataTable.dictLabel().ilikeIf(input.getDictLabel())
                ).orderBy(dataTable.dictSort().asc())
                .select(dataTable.fetch(SysDictDataPageView.class))
                .fetchPage(pageQuery.getPageNum(), pageQuery.getPageSize());
    }
}
